<template>
  <div class="index-box">
    <div class="content-head">
      <a-row align="middle">
        <a-col span="12">
          <a-button type="primary" icon="plus" style="margin-right: 8px;" @click="() => { $router.push({name:'data_parking_operation',params:{id:'add'}}) }">添加</a-button>
          <a-button type="primary" style="margin-right: 8px;" @click="() => { $router.push({name:'parking-import'}) }">导入</a-button>
          <a-button style="margin-right: 8px;" :disabled="$common.isEmpty(selectedRowKeys)" @click="$router.push({name:'data_parking_bz',params:{id:selectedRowKeys.join(',')}})">添加收费标准</a-button>
          <a-popconfirm title="确定要删除当前所选车位?" @confirm="delParking()">
            <a-button :disabled="$common.isEmpty(selectedRowKeys)">删除</a-button>
          </a-popconfirm>
        </a-col>
        <a-col span="12">
          <a-input-search style="width:200px;float:right;position: static;padding-right: 5px"  placeholder="请输入车位号" enterButton @search="onSearch($event,3)"/>
          <a-select style="width:150px;float:right;position: static;padding-right: 5px" :options="communityList" @change="onSearch($event,1)" placeholder="请选小区" />
          <a-select style="width:150px;float:right;position: static;padding-right: 5px" :options="carStatusOption" @change="onSearch($event,2)" placeholder="请选择车位状态" />
        </a-col>
      </a-row>
    </div>
    <div class="content-body">
      <s-table ref="table" :columns="columns" :pageURI='true' :data="dataSource" :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" rowKey="id" :loading="loading">
        <template slot="type" slot-scope="text,record">
          {{carTypeList.find((value,index,array) => value.id === record.type).name}}
        </template>
        <template slot="status" slot-scope="text,record">
          <a-badge :status="badgeStatus[record.status - 1]" /><span>{{carStatusList.find((value,index,array) => value.id === record.status).name}}</span>
        </template>
        <template slot="operation" slot-scope="text,record">
          <a-dropdown>
            <a class="ant-dropdown-link" href="javascript:void(0);">操作 <a-icon type="down" /></a>
            <a-menu slot="overlay" @click="operation($event,record)">
              <a-menu-item key="1">详情</a-menu-item>
              <a-menu-item key="2">绑定住户</a-menu-item>
              <a-menu-item key="3">添加收费标准</a-menu-item>
              <a-menu-item key="4">编辑</a-menu-item>
              <a-menu-item key="5">
                <a-popconfirm title="确定要删除当前所选车位?" @confirm="delParking([record.id])">
                  <a href="javascript:void(0);">删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </s-table>
    </div>
    <a-modal title="绑定住户" v-model="bindUserModal" :confirmLoading="bindUserModalLoading" :afterClose="() => { form.resetFields(); }" @ok="handleSubmit">
      <a-form :form="form" @submit="handleSubmit">
        <a-form-item label="所属小区" :labelCol="{xs:{span:24},sm:{span:6}}" :wrapperCol="{xs:{span:24},sm:{span:16}}">
          <span>{{bd_name}}</span>
        </a-form-item>
        <a-form-item label="选择住户" :labelCol="{xs:{span:24},sm:{span:6}}" :wrapperCol="{xs:{span:24},sm:{span:16}}">
          <a-select placeholder="输入并选择要绑定的住户，可多选" @focus="clearUserList" @search="getBindUserList" :notFoundContent="fetching ? undefined : '无匹配结果'" allowClear optionFilterProp="children" mode="multiple" v-decorator="['house_user_id',{rules:[{required:true,message:'请选择住户'}],initialValue:[]}]" >
            <a-spin v-if="fetching" slot="notFoundContent" size="small" />
            <a-select-option v-for="item in bindUserList" :key="item.value">{{item.label}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item style="display: none;">
          <a-input type="hidden" v-decorator="['car_area_id',{rules:[{required:true,message:'车位id不可为空'}],initialValue:''}]" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
  import { ACCESS_TOKEN } from '@/store/mutation-types'
  import {STable} from '@/components'
  export default {
    name: 'data_parking_index',
    data() {
      return {
        token:this.$ls.get(ACCESS_TOKEN),
        loading:false,
        bindUserModal:false,
        bindUserModalLoading:false,
        communityList:[],
        bd_info_id:'', // 小区id
        bd_name:'', // 所属小区
        bindUserList:[], // 住户列表
        fetching:false,
        carStatusOption:[{value:0,label:'全部'},{value:1,label:'出售'},{value:2,label:'出租'},{value:3,label:'空置'},{value:4,label:'自用'},{value:5,label:'待售'},{value:6,label:'待租'},{value:7,label:'临停'}],
        form:this.$form.createForm(this),
        badgeStatus:['error','processing','default','success','warning','warning','warning'],
        carTypeList:[{id:1,name:'人防车位'},{id:2,name:'公共车位'},{id:3,name:'产权车位'}],
        carStatusList:[{id:1,name:'出售'},{id:2,name:'出租'},{id:3,name:'空置'},{id:4,name:'自用'},{id:5,name:'待售'},{id:6,name:'待租'},{id:7,name:'临停'}],
        columns:[
          {
            title:'车位编号',
            dataIndex:'id'
          },
          {
            title: '所属小区',
            dataIndex:'bd_name'
          },
          {
            title: '车位号',
            dataIndex:'name'
          },
          {
            title: '车位类型',
            dataIndex:'type',
            scopedSlots:{customRender:'type'}
          },
          {
            title: '车位状态',
            dataIndex:'status',
            scopedSlots:{customRender:'status'}
          },
          {
            title: '车位面积',
            dataIndex:'area'
          },
          {
            title: '收费标准个数',
            dataIndex:'bz_number'
          },
          {
            title: '备注',
            dataIndex:'remarks'
          },
          {
            title: '操作',
            dataIndex:'operation',
            scopedSlots:{customRender:'operation'}
          }
        ],
        queryParam:{},
        cur_page:0,
        dataSource:parameter => {
          this.cur_page=parameter.pageNo
          return this.getList(Object.assign(parameter, this.queryParam))
            .then(res => {
              return res
            })
        },
        selectedRowKeys: []
      }
    },
    mounted() {
      this.getCommunity();
    },
    components:{STable},
    methods:{
      // 车位列表
      getList(param) {
        return new Promise((resolve, reject) => {
          this.loading = true;
          this.axios({
            method:'post',
            url:'/parking/getList',
            data:Object.assign(param,{token:this.token})
          }).then(res => {
            resolve(res.data);
          }).catch(err => {
            this.$message.error('服务器发生错误...',2);
          }).finally(() => {
            this.loading = false;
          });
        });
      },
      // 车位筛选
      onSearch(val,key) {
        if(key==1){
          this.queryParam['bd_info_id']=val
        }else if(key==2){
          this.queryParam['status']=val
        }else{
          this.queryParam['name'] = val;
          this.$refs.table.refresh(true);
        }
        
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
      },
      getCommunity(){
        this.axios({
          method:'post',
          url:'/parking/getAllCommunityList',
          data:{token:this.token}
        }).then(res => {
          if(res.code === 0){
              let ifo = {value:0,label:'所有小区'};
              res.data.unshift(ifo);
            this.communityList = res.data;
          }else this.$message.warning(res.msg);
        }).catch(err => {
          this.$message.error('服务器发生错误...');
        })
      },
      // 车位操作
      operation({ key },info) {
        const _this = this;
        _this.bd_name = info.bd_name;
        _this.bd_info_id = info.bd_info_id;
        if(key === '1') _this.$router.push({name:'data_parking_detail',params:{id:info.id,cur_page:this.cur_page}});
        if(key === '2'){
          _this.bindUserModal = true;
          _this.$nextTick(() => {
            _this.form.setFieldsValue({car_area_id:info.id});
          });
        }
        if(key === '3') _this.$router.push({name:'data_parking_bz',params:{id:String(info.id)}});
        if(key === '4') _this.$router.push({name:'data_parking_operation',params:{id:info.id}});
      },
      // 删除车位
      delParking(ids = this.selectedRowKeys) {
        this.axios({
          method:'post',
          url:'/parking/delParking',
          data:{token:this.token,ids},
        }).then(res => {
          if(res.code === 0){
            this.$message.success(res.msg,2);
            this.$refs.table.refresh();
          }else this.$message.warning(res.msg,2);
        }).catch(err => {
          this.$message.error('服务器发生错误...',2);
        })
      },
      // 确定提交
      handleSubmit(e) {
        e.preventDefault();
        this.form.validateFields((err, values) => {
          if (err) {
            for (let key in err) {
              for (let item of err[key]['errors']) return this.$message.warning(item['message'], 2)
            }
          }
          Object.assign(values,{token:this.token});
          this.bindUserModalLoading = true;
          this.axios({
            method: 'post',
            url: '/parking/bindUser',
            data: values
          }).then(res => {
            if (res.code == 0) {
              this.$message.success('绑定成功', 1)
              this.bindUserModal = false;
            } else this.$message.warning(res.msg)
          }).catch(() => {
            this.$message.error('服务器发生错误...', 2);
          }).finally(() => {
            this.bindUserModalLoading = false;
          })
        })
      },
      clearUserList(){
        this.bindUserList = [];
      },
      // 获取绑定住户列表
      getBindUserList(value) {
        if (value && value.length > 1) {
          this.fetching = true;
          this.axios({
            method: "post",
            url: "/parking/getBindUserList",
            data: { id: this.form.getFieldValue('car_area_id'), bd_info_id: this.bd_info_id, token: this.token,text:value,type:1 }
          }).then(res => {
            if(res.code==0){
              this.bindUserList = res.data;
            }else{
              this.bindUserList = [];
              this.$message.error(res.msg);
            }
          }).catch(err => {
            this.$message.error('服务器发生错误...');
          }).finally(() => {
            this.fetching = false;
          })
        }else this.bindUserList = [];
      }
    }
  }
</script>

<style lang="less" scoped>
  .index-box{
    background: #ffffff;
    padding: 25px;
    box-sizing: border-box;
    .content-body{
      padding-top:20px;
    }
  }
</style>